package com.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author zooy
 * @since 2024/6/25-17:40
 */
@Service
@Slf4j
public class MessageCodeService {

    private Map<String, String> phoneCodeCache = new HashMap<>();

    public String sendMessage(String phoneNumber) {

        // 给手机发送短信验证码
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
                .accessKeyId("LTAI5tM3wayn58GsvLGnkkdp")
                .accessKeySecret("RyqHKJPPFg3PEA3Mi8fdRRaxeK4V1O")
                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // Parameter settings for API request
        String code = RandomUtil.randomNumbers(6);
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(phoneNumber)
                .signName("旅游信息网站")
                .templateCode("SMS_468560056")
                .templateParam("{\"code\":\"" + code + "\"}")
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        SendSmsResponse resp = null;
        try {
            resp = response.get();

            // 判断返回消息
            if(resp.getBody().getCode().equals("OK")){
                // 短信发送成功
                // 插入缓存中
                phoneCodeCache.put(phoneNumber, code);
                return null;
            } else{
                // 短信发送失败
                // 返回失败消息
                return resp.getBody().getMessage();
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        } finally {
            client.close();
        }

    }

    public String sendMessageLocal(String phoneNumber) {

        String code = RandomUtil.randomNumbers(6);
        log.info("send message code is {}", code);
        phoneCodeCache.put(phoneNumber, code);
        return null;
    }


    /**
     * 获取短信验证码
     * @param phoneNumber
     * @return
     */
    public String getPhoneCode(String phoneNumber) {
        return phoneCodeCache.get(phoneNumber);
    }

}
